<?php

namespace iBrand\Shop\Backend\Http\Controllers;

use iBrand\Component\User\Models\User;
use Illuminate\Http\Request;
use iBrand\Shop\Backend\Model\Shop;
use iBrand\Shop\Backend\Model\Common;
use Maatwebsite\Excel\Facades\Excel;
use iBrand\Shop\Backend\Repository\CityRepository;
use iBrand\Shop\Backend\Repository\TagRepository;
use iBrand\Shop\Backend\Repository\ActivityRepository;
use iBrand\Shop\Backend\Repository\StoreRepository;
use DB;
use Encore\Admin\Facades\Admin as LaravelAdmin;
use Encore\Admin\Layout\Content;

class StoreController extends Controller
{
	protected $upload_dir;
	protected $upload_url;
	protected $city;
	protected $tag;
	protected $activity;
	protected $store;

	function __construct(CityRepository $cityRepository,
	                     TagRepository $tagRepository,
	                     ActivityRepository $activityRepository,
	                     StoreRepository $storeRepository)
	{
		$this->upload_dir = storage_path('storelocator/');
		$this->upload_url = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/storelocator/';
		$this->city       = $cityRepository;
		$this->tag        = $tagRepository;
		$this->activity   = $activityRepository;
		$this->store      = $storeRepository;
	}

	public function storeList()
	{
		$where = [];
		if (!empty(request('name'))) {
			$where['name'] = ['like', '%' . trim(request('name')) . '%'];
		}

		if (!empty(request('phone'))) {
			$where['phone'] = ['like', '%' . trim(request('phone')) . '%'];
		}

		if (!empty(request('city'))) {
			$where['city_id'] = ['=', trim(request('city'))];
		}

		$data = $this->store->getStorePaginated($where);

		$cities = $this->city->getCitys();

		return LaravelAdmin::content(function (Content $content) use ($data, $cities) {

			$content->header('门店列表');

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店列表', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '门店列表']

			);

			$content->body(view('shop-backend::store.store_list', compact('data', 'cities')));
		});
	}

	public function storeCurd($id = 0)
	{
		$store = [];
		if ($id) {
			$store = $this->store->find($id);
		}

		$citys = $this->city->getCitys();

		return LaravelAdmin::content(function (Content $content) use ($store, $citys, $id) {

			$header = '添加门店';
			if ($id) {
				$header = '编辑门店';
			}
			$content->header($header);

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => $header, 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '门店列表']

			);

			$content->body(view('shop-backend::store.store_create', compact('store', 'citys')));
		});
	}

	public function storeSave(Request $request)
	{
		$input   = $request->except('_token', 'file');
		$code    = 500;
		$message = '保存失败';
		$data    = [
			'name'    => $input['store-name'],
			'city_id' => $input['store-city'],
			'address' => $input['store-address'],
			'phone'   => isset($input['store-phone']) ? $input['store-phone'] : '',
			'top'     => isset($input['store-top']) ? $input['store-top'] : 1,
		];

		$data['code']      = isset($input['store-code']) ? $input['store-code'] : '';
		$data['is_enable'] = isset($input['store-is_enable']) ? $input['store-is_enable'] : 1;
		$data['img']       = $input['img_name'];

		/*定位功能*/
		$geocoder = Common::_store_qq_geocoder(trim($data['address']));
		if ($geocoder == null) {
			$data['lat'] = '';
			$data['lng'] = '';
		} else {
			if ($geocoder->status == 0) {
				$data['lat'] = $geocoder->result->location->lat;
				$data['lng'] = $geocoder->result->location->lng;
			} else {
				$data['lat'] = '';
				$data['lng'] = '';
			}
		}

		try {
			DB::beginTransaction();
			if ($input['store-id']) {
				$res = $this->store->update($data, $input['store-id']);
			} else {
				$res = $this->store->create($data);
			}
			if ($res && $res->id) {
				$code    = 200;
				$message = '保存成功';
			}
			DB::commit();
		} catch (\Exception $exception) {
			DB::rollBack();
			\Log::info($exception);

			return $this->ajaxJson(false, [], 404, '保存失败');
		}

		return $this->ajaxJson(true, [], $code, $message);
	}

	public function tagList()
	{
		$where = [];
		if (!empty(request('name'))) {
			$where['name'] = ['like', '%' . trim(request('name')) . '%'];
		}

		$data = $this->tag->getTagPaginated($where);

		return LaravelAdmin::content(function (Content $content) use ($data) {

			$content->header('标签列表');

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '标签列表', 'left-menu-active' => '标签管理']
			);

			$content->body(view('shop-backend::store.tag_list', compact('data')));
		});
	}
	
	public function tagCurd($id = 0)
	{
		$tag = [];
		if ($id) {
			$tag = $this->tag->find($id);
		}

		return LaravelAdmin::content(function (Content $content) use ($tag, $id) {

			$header = '创建门店标签';
			if ($id) {
				$header = '编辑门店标签';
			}

			$content->header($header);

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => $header, 'left-menu-active' => '标签管理']
			);

			$content->body(view('shop-backend::store.tag_create', compact('tag')));
		});
	}

	public function tagSave(Request $request)
	{
		$input             = $request->except('_token');
		$code              = 500;
		$message           = '保存失败';
		$data              = [];
		$data['name']      = $input['store-tag-name'];
		$data['url']       = isset($input['store-tag-url']) ? $input['store-tag-url'] : '';
		$data['top']       = isset($input['store-tag-top']) ? $input['store-tag-top'] : 1;
		$data['point_img'] = isset($input['store-tag-point_img']) ? $input['store-tag-point_img'] : 1;
		$data['sort']      = isset($input['store-tag-sort']) && $input['store-tag-sort'] ? $input['store-tag-sort'] : 1;
		$data['code']      = generate_random_string(6);;
		if ($input['store-tag-img'] != null) {
			$file = $this->storelocator_upload('tag');
			if ($request->file('store-tag-img')->isValid()) {
				$request->file('store-tag-img')->move($file['destinationPath'], $file['fileName']);
			}

			$data['file']     = $file['file'];
			$data['file_url'] = $file['file_url'];
		}

		if ($input['store-tag-id']) {
			$res = $this->tag->update($data, $input['store-tag-id']);
		} else {
			$res = $this->tag->create($data);
		}

		if ($res && $res->id) {
			$code    = 200;
			$message = '保存成功';
		}

		return $this->ajaxJson(true, [], $code, $message);
	}

	public function cityList()
	{
		$where = [];
		if (!empty(request('name'))) {
			$where['name'] = ['like', '%' . trim(request('name')) . '%'];
		}

		$data = $this->city->getCityPaginated($where);

		return LaravelAdmin::content(function (Content $content) use ($data) {

			$content->header('城市列表');

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '城市列表', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '城市管理']

			);

			$content->body(view('shop-backend::store.city_list', compact('data')));
		});
	}

	public function cityCurd($id = 0)
	{
		$city = [];
		if ($id) {
			$city = $this->city->find($id);
		}

		return LaravelAdmin::content(function (Content $content) use ($city, $id) {

			$header = '添加城市';
			if ($id) {
				$header = '编辑城市';
			}

			$content->header($header);

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => $header, 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '城市管理']

			);

			$content->body(view('shop-backend::store.city_create', compact('city')));
		});
	}

	/**
	 * 添加城市
	 *
	 * @param \Illuminate\Http\Request $request
	 *
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function citySave(Request $request)
	{
		$input   = $request->except('_token');
		$code    = 500;
		$message = '保存失败';

		$data         = [];
		$data['name'] = $input['store-city-name'];
		$check        = $this->city->findWhere(['name' => $data['name']])->first();
		if ($check) {
			$message = '城市名称已存在';

			return $this->ajaxJson(true, [], $code, $message);
		}

		$data['letter'] = $input['store-city-letter'];
		$geocoder       = Common::_store_qq_geocoder($input['store-city-name']);
		if ($geocoder->status === 0) {
			$data['lat'] = $geocoder->result->location->lat;
			$data['lng'] = $geocoder->result->location->lng;
		}

		if ($input['store-city-id']) {
			$res = $this->city->update($data, $input['store-city-id']);
		} else {
			$res = $this->city->create($data);
		}

		if ($res && $res->id) {
			$code    = 200;
			$message = '保存成功';
		}

		return $this->ajaxJson(true, [], $code, $message);
	}

	/**
	 * 定位点修复功能
	 *
	 * @return mixed
	 */
	public function point()
	{
		set_time_limit(0);
		$store = $this->store->findWhere([['lat', '<=', 0]]);
		if (count($store) > 0) {
			foreach ($store as $value) {
				$geocoder = Common::_store_qq_geocoder(trim($value->address));
				if (is_object($geocoder)) {
					if ($geocoder->status == 0) {
						$edit['lng'] = $geocoder->result->location->lng;
						$edit['lat'] = $geocoder->result->location->lat;
						$this->store->update($edit, $value->id);
					}
				}
			}
		}

		$city = $this->city->findWhere([['lat', '<=', 0]]);
		if (count($city) > 0) {
			foreach ($city as $value) {
				$geocoder = Common::_store_qq_geocoder(trim($value->name));
				if (is_object($geocoder)) {
					if ($geocoder->status == 0) {
						$edit['lat'] = $geocoder->result->location->lat;
						$edit['lng'] = $geocoder->result->location->lng;
						$this->store->update($edit, $value->id);
					}
				}
			}
		}

		return $this->ajaxJson(true, [], 200, '定位点修复成功');
	}

	public function system(Request $request)
	{
		if ($request->isMethod('post')) {
			$input = $request->except('_token');
			if (!empty($input['storeSystemConfig'])) {
				settings()->setSetting($input);

				return $this->ajaxJson(true, [], 200, '保存成功');
			}
		}

		$storeSystemConfig = settings('storeSystemConfig');
		if (!is_array($storeSystemConfig)) {
			$storeSystemConfig = [];
		}

		return LaravelAdmin::content(function (Content $content) use ($storeSystemConfig) {

			$content->header('门店基本信息');

			$content->breadcrumb(
				['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
				['text' => '基础设置', 'url' => 'shop/store/system', 'no-pjax' => 1],
				['text' => '门店基本信息', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '基本信息']

			);

			$content->body(view('shop-backend::store.system', compact('storeSystemConfig')));
		});
	}

	public function search(Request $request)
	{
		if ($request->isMethod('post')) {
			Shop::saveSearchs($request->input('shop_ids'));

			return redirect()->route('admin.shop.list.store')->withFlashSuccess('搜索推荐门店设置成功');
		}

		$searchs = Shop::getSearchs();
		$ids     = [];
		if (!empty($searchs)) {
			foreach ($searchs as $search) {
				$ids[] = $search->shop_id;
			}
		}

		$data['select'] = $ids;
		$data['search'] = Shop::getStorelocatorAct_City_Shop();

		return LaravelAdmin::content(function (Content $content) use ($data) {

			$content->body(view('shop-backend::store.search', compact('data')));
		});
	}

	/**
	 * 删除 根据type选择删除
	 *
	 * @param Request $request
	 */
	public function del(Request $request)
	{
		if ($request->isMethod('post')) {
			$obj     = null;
			$check   = null;
			$type    = $request->input('type');
			$id      = $request->input('id');
			$code    = 200;
			$message = '删除成功';

			switch ($type) {
				case 'list':
					$obj = $this->store;
					break;
				case 'tag':
					$obj = $this->tag;
					break;
				case 'act':
					$obj     = $this->activity;
					$check   = $this->store->findWhere(['act' => $id])->first();
					$message = '该活动已有门店选择,无法删除';
					break;
				case 'city':
					$obj     = $this->city;
					$check   = $this->store->findWhere(['city' => $id])->first();
					$message = '该城市已添加门店,无法删除';
					break;
			}

			if ($obj) {
				if (count($check) > 0) {
					$code = 500;

					return $this->ajaxJson(true, [], $code, $message);
				}

				$obj->delete($id);

				return $this->ajaxJson(true, [], $code, $message);
			}
		}
	}

	/**
	 * 清理过期活动与产品的挂钩
	 */
	public function cron_act()
	{
		$result = $this->activity->findWhere([['act_endtime', '>', date('Y-m-d')]]);
		if (count($result) > 0) {
			foreach ($result as $value) {
				$this->store->update(['act' => 0], $value->id);
			}
		}
	}

	/**
	 * 图片参数生成
	 *
	 * @param type $type
	 *
	 * @return string
	 */
	private function storelocator_upload($type)
	{
		$data     = [];
		$typefile = $type . '/' . date('Y_m_d');
		if (!file_exists($this->upload_dir . $typefile)) {
			mkdir($this->upload_dir . $typefile, 0777, true);
		}
		$data['fileName']        = '/' . date('Y_m_d') . '_' . rand(1, 100) . '.jpg';
		$data['file']            = $this->upload_dir . $typefile . $data['fileName'];
		$data['file_url']        = $this->upload_url . $typefile . $data['fileName'];
		$data['destinationPath'] = $this->upload_dir . $typefile;

		return $data;
	}

}
